///
/// 输入框组件
/// 参照Element UI的Input控件实现

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../core/elegance_theme.dart';
import '../../core/elegance_base.dart';

/// 输入框大小类型枚举
enum EInputSize {
  /// 小型输入框
  small,
  
  /// 普通大小输入框
  normal,
  
  /// 大型输入框
  large,
}

/// 输入框类型枚举
enum EInputType {
  /// 文本输入
  text,
  
  /// 数字输入
  number,
  
  /// 密码输入
  password,
  
  /// 多行文本输入
  textarea,
  
  /// 邮箱输入
  email,
  
  /// 电话输入
  tel,
  
  /// URL输入
  url,
}

/// 简化版EInput组件
class EInput extends StatefulWidget {
  /// 创建EInput组件
  const EInput({
    super.key,
    this.type = EInputType.text,
    this.value,
    this.onChange,
    this.placeholder,
    this.size = EInputSize.normal,
    this.disabled = false,
    this.clearable = false,
    this.showPassword = false,
    this.readonly = false,
    this.maxlength,
    this.showWordLimit = false,
    this.prefixIcon,
    this.suffixIcon,
    this.prefix,
    this.suffix,
    this.label,
    this.formatter,
  });

  /// 输入框类型
  final EInputType type;
  
  /// 绑定值
  final String? value;
  
  /// 输入值改变时的回调
  final ValueChanged<String>? onChange;
  
  /// 占位符
  final String? placeholder;
  
  /// 输入框大小
  final EInputSize size;
  
  /// 是否禁用
  final bool disabled;
  
  /// 是否可清空
  final bool clearable;
  
  /// 是否显示密码可见性切换按钮
  final bool showPassword;
  
  /// 是否只读
  final bool readonly;
  
  /// 最大输入长度
  final int? maxlength;
  
  /// 是否显示输入字数统计
  final bool showWordLimit;
  
  /// 输入框前置图标
  final Widget? prefixIcon;
  
  /// 输入框后置图标
  final Widget? suffixIcon;
  
  /// 输入框前置内容
  final Widget? prefix;
  
  /// 输入框后置内容
  final Widget? suffix;
  
  /// 输入框标签
  final String? label;
  
  /// 输入格式化器
  final List<TextInputFormatter>? formatter;

  @override
  State<EInput> createState() => _EInputState();
}

class _EInputState extends State<EInput> with ThemedMixin {
  /// 输入框控制器
  final TextEditingController _controller = TextEditingController();
  
  /// 焦点节点
  final FocusNode _focusNode = FocusNode();
  
  /// 是否聚焦
  bool _isFocused = false;
  
  /// 密码是否可见
  bool _passwordVisible = false;

  @override
  void initState() {
    super.initState();
    
    // 初始化控制器
    if (widget.value != null) {
      _controller.text = widget.value!;
    }
    
    // 监听控制器文本变化
    _controller.addListener(() {
      if (widget.onChange != null) {
        widget.onChange!(_controller.text);
      }
    });
    
    // 监听焦点变化
    _focusNode.addListener(() {
      setState(() {
        _isFocused = _focusNode.hasFocus;
      });
    });
    
    // 初始化密码可见性
    _passwordVisible = false;
  }

  @override
  void didUpdateWidget(covariant EInput oldWidget) {
    super.didUpdateWidget(oldWidget);
    
    // 当外部value变化时，更新控制器
    if (oldWidget.value != widget.value && widget.value != _controller.text) {
      _controller.text = widget.value ?? '';
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  /// 处理清空按钮点击
  void _handleClear() {
    _controller.clear();
    if (widget.onChange != null) {
      widget.onChange!('');
    }
  }

  /// 处理密码可见性切换
  void _togglePasswordVisibility() {
    setState(() {
      _passwordVisible = !_passwordVisible;
    });
  }

  /// 获取输入框高度
  double _getInputHeight() {
    switch (widget.size) {
      case EInputSize.small:
        return 32.0;
      case EInputSize.large:
        return 40.0;
      default:
        return 36.0;
    }
  }

  /// 获取字体大小
  double _getFontSize() {
    switch (widget.size) {
      case EInputSize.small:
        return 12.0;
      case EInputSize.large:
        return 16.0;
      default:
        return 14.0;
    }
  }

  /// 获取边距
  EdgeInsets _getContentPadding() {
    switch (widget.size) {
      case EInputSize.small:
        return const EdgeInsets.symmetric(horizontal: 10, vertical: 6);
      case EInputSize.large:
        return const EdgeInsets.symmetric(horizontal: 14, vertical: 12);
      default:
        return const EdgeInsets.symmetric(horizontal: 12, vertical: 8);
    }
  }

  /// 获取边框颜色
  Color _getBorderColor() {
    if (widget.disabled) {
      return theme.borderColor.withOpacity(0.5);
    }
    
    if (_isFocused) {
      return theme.primaryColor;
    }
    
    return theme.borderColor;
  }

  /// 获取背景颜色
  Color _getBackgroundColor() {
    if (widget.disabled) {
      return theme.backgroundColor;
    }
    
    return Colors.white;
  }

  /// 获取输入框类型
  TextInputType _getKeyboardType() {
    switch (widget.type) {
      case EInputType.number:
        return TextInputType.number;
      case EInputType.email:
        return TextInputType.emailAddress;
      case EInputType.tel:
        return TextInputType.phone;
      case EInputType.url:
        return TextInputType.url;
      case EInputType.textarea:
        return TextInputType.multiline;
      default:
        return TextInputType.text;
    }
  }

  @override
  Widget build(BuildContext context) {
    final height = widget.type == EInputType.textarea ? null : _getInputHeight();
    final fontSize = _getFontSize();
    final contentPadding = _getContentPadding();
    final borderColor = _getBorderColor();
    final backgroundColor = _getBackgroundColor();
    
    // 构建装饰器
    InputDecoration decoration = InputDecoration(
      border: OutlineInputBorder(
        borderSide: BorderSide(color: borderColor, width: 1),
        borderRadius: BorderRadius.circular(4),
      ),
      enabledBorder: OutlineInputBorder(
        borderSide: BorderSide(color: borderColor, width: 1),
        borderRadius: BorderRadius.circular(4),
      ),
      focusedBorder: OutlineInputBorder(
        borderSide: BorderSide(color: theme.primaryColor, width: 1),
        borderRadius: BorderRadius.circular(4),
      ),
      contentPadding: contentPadding,
      hintText: widget.placeholder,
      hintStyle: TextStyle(
        fontSize: fontSize,
        color: theme.textPlaceholderColor,
      ),
      prefixIcon: widget.prefixIcon,
      suffixIcon: _buildSuffixIcon(),
      prefix: widget.prefix,
      suffix: widget.suffix,
    );
    
    // 构建输入框
    Widget inputWidget = TextField(
      controller: _controller,
      focusNode: _focusNode,
      decoration: decoration,
      style: TextStyle(
        fontSize: fontSize,
        color: theme.textPrimaryColor,
      ),
      enabled: !widget.disabled,
      readOnly: widget.readonly,
      maxLength: widget.maxlength,
      obscureText: widget.type == EInputType.password && !_passwordVisible,
      keyboardType: _getKeyboardType(),
      maxLines: widget.type == EInputType.textarea ? null : 1,
      minLines: widget.type == EInputType.textarea ? 3 : 1,
      inputFormatters: widget.formatter,
    );
    
    // 构建最终组件
    List<Widget> resultWidgets = [];
    
    if (widget.label != null) {
      resultWidgets.add(
        Text(
          widget.label!,
          style: TextStyle(
            fontSize: fontSize,
            color: theme.textRegularColor,
          ),
        ),
      );
      resultWidgets.add(const SizedBox(height: 4));
    }
    
    resultWidgets.add(inputWidget);
    
    if (widget.showWordLimit && widget.maxlength != null) {
      resultWidgets.add(const SizedBox(height: 4));
      resultWidgets.add(
        Text(
          '${_controller.text.length}/${widget.maxlength}', 
          style: TextStyle(
            fontSize: 12,
            color: theme.textSecondaryColor,
          ),
        ),
      );
    }
    
    return Container(
      width: double.infinity,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: resultWidgets,
      ),
    );
  }
  
  /// 构建后缀图标
  Widget? _buildSuffixIcon() {
    List<Widget> suffixIcons = [];
    
    if (widget.suffixIcon != null) {
      suffixIcons.add(widget.suffixIcon!);
    }
    
    // 添加密码可见性切换按钮
    if (widget.type == EInputType.password && widget.showPassword) {
      if (suffixIcons.isNotEmpty) {
        suffixIcons.add(const SizedBox(width: 8));
      }
      suffixIcons.add(
        IconButton(
          icon: Icon(
            _passwordVisible ? Icons.visibility_off : Icons.visibility,
            size: 18,
            color: theme.textSecondaryColor,
          ),
          onPressed: _togglePasswordVisibility,
          padding: EdgeInsets.zero,
          constraints: const BoxConstraints(),
        ),
      );
    }
    
    // 添加清空按钮
    if (widget.clearable && _controller.text.isNotEmpty && !widget.disabled && !widget.readonly) {
      if (suffixIcons.isNotEmpty) {
        suffixIcons.add(const SizedBox(width: 8));
      }
      suffixIcons.add(
        IconButton(
          icon: Icon(
            Icons.clear,
            size: 16,
            color: theme.textSecondaryColor,
          ),
          onPressed: _handleClear,
          padding: EdgeInsets.zero,
          constraints: const BoxConstraints(),
        ),
      );
    }
    
    if (suffixIcons.isEmpty) {
      return null;
    }
    
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: suffixIcons,
    );
  }
}

/// 输入验证规则类
class InputValidationRule {
  /// 创建输入验证规则
  InputValidationRule({
    required this.validate,
    required this.errorMessage,
  });
  
  /// 验证函数
  final bool Function(String) validate;
  
  /// 错误信息
  final String errorMessage;
}

/// 常用验证规则工具类
enum InputValidationPattern {
  /// 邮箱验证
  email(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\$', '请输入有效的邮箱地址'),
  
  /// 手机号验证
  phone(r'^1[3-9]\d{9}\$', '请输入有效的手机号码'),
  
  /// 整数验证
  integer(r'^-?\d+\$', '请输入整数');
  
  const InputValidationPattern(this.regex, this.errorMessage);
  
  final String regex;
  final String errorMessage;
  
  /// 创建验证规则
  InputValidationRule toRule() {
    final RegExp regExp = RegExp(regex);
    return InputValidationRule(
      validate: (value) => regExp.hasMatch(value),
      errorMessage: errorMessage,
    );
  }
}